package org.zn.note.designpattern;

/**
 * 业务代表模式（Business Delegate Pattern）
 * 用于对表示层和业务层解耦
 */
public class Pattern27_BusinessDelegate {

    public static void main(String[] args) {
        // 业务代表
        BusinessDelegate businessDelegate = new BusinessDelegate();
        businessDelegate.setServiceType("EJB");
        // 客户端
        Client client = new Client(businessDelegate);
        client.doTask();

        businessDelegate.setServiceType("JMS");
        client.doTask();
    }

    private interface BusinessService {
        void doProcessing();
    }

    private static class EJBService implements BusinessService {
        @Override
        public void doProcessing() {
            System.out.println("Processing task by invoking EJB Service");
        }
    }

    private static class JMSService implements BusinessService {
        @Override
        public void doProcessing() {
            System.out.println("Processing task by invoking JMS Service");
        }
    }

    // 业务查询服务
    private static class BusinessLookUp {
        BusinessService getBusinessService(String serviceType) {
            if (serviceType.equalsIgnoreCase("EJB")) {
                return new EJBService();
            } else {
                return new JMSService();
            }
        }
    }

    // 业务代表
    private static class BusinessDelegate {
        private BusinessLookUp lookupService = new BusinessLookUp();
        private BusinessService businessService;
        private String serviceType;

        void setServiceType(String serviceType) {
            this.serviceType = serviceType;
        }

        void doTask() {
            businessService = lookupService.getBusinessService(serviceType);
            businessService.doProcessing();
        }
    }

    // 客户端
    private static class Client {

        BusinessDelegate businessService;

        public Client(BusinessDelegate businessService) {
            this.businessService = businessService;
        }

        public void doTask() {
            businessService.doTask();
        }
    }
}
